const express = require('express');
const app = express();

const getData = require('./mqtt.js')


const db = require('./sql/db.js')

const md5 = require('md5');
const jwt = require('jsonwebtoken');


//cors中间件，解决跨域问题
const cors = require('cors');
app.use(cors());

//解析请求体
app.use(express.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded


//查询传感器数据
app.get('/getTemData', (req, res) => {
  db('SELECT * from temdata', (err, result) => {
    if(err) throw err;
    res.send({'status': 200, message: '获取数据成功', data: result});
  })

})

//查询设备数据
app.get('/queryDevice', (req, res) => {
  db('select * from sensor', (err, result) => {
    if(err) throw err;
    res.send({'status': 200, message: '获取设备信息成功', data: result});
  })
})

//安卓采集端接口
app.get('/serve', (req, res) => {
  getData(req.query);
  res.send('ok')
})

//------用户相关接口-----------
app.get('/getUser', (req, res) => {
  db('select * from user', (err, result) => {
    if (err) throw err;
    res.send({'status': 200, message: '获取用户信息成功', data: result});
  })
})



//----------用户注册接口---------
// 注册接口
app.post('/reguser', (req, res) => {
  console.log(req.body);
  let {username, password} = req.body;
  //密码进行md5加密
  password = md5(password);
  // 验证用户名是否存在
  db(`select * from user where username='${username}'`, (err, result) => {
    if(err) throw err;
    if(result.length > 0) {
      res.send({status: 1, message: '账号已存在'});
    }else {
      //注册成功，添加注册信息到数据库
      db(`insert into user set username='${username}', password='${password}'`, (err, result) => {
        if(err) throw err;
        res.send({status: 200, message: '注册成功'});
      })
    }
  })
});


//--------用户登录接口---------
app.post('/login', (req, res) => {
  let {username, password} = req.body;
  //密码进行md5加密
  password = md5(password);
  // 验证用户名和密码是否匹配
  db(`select * from user where username='${username}' and password='${password}'`, (err, result) => {
    if(err) throw err;
    if(result.length > 0) {
      //登录成功，创建token
      // let token = jwt.sign(对象格式的数据， 字符串格式的key, 对象格式的配置项 )
      let token = jwt.sign({id: result[0].id}, 'gjhfjkdsjfhdcvfgq3fdsf', {expiresIn: '2h'});
      res.send({status: 200, message: '登录成功', token: `Bearer ${token}`});
    }else {
      res.send({status: 1, message: '账号或密码错误'})
    }
  })
});


//-------管理员登录接口--------
app.post('/alogin', (req, res) => {
  let {username, password} = req.body;
  //密码进行md5加密
  password = md5(password);
  // 验证用户名和密码是否匹配
  db(`select * from admin where username='${username}' and password='${password}'`, (err, result) => {
    if(err) throw err;
    if(result.length > 0) {
      //登录成功，创建token
      // let token = jwt.sign(对象格式的数据， 字符串格式的key, 对象格式的配置项 )
      let token = jwt.sign({id: result[0].id}, 'gjhfjkdsjfhdcvfgq3fdsf', {expiresIn: '2h'});
      res.send({status: 200, message: '登录成功', token: `Bearer ${token}`});
    }else {
      res.send({status: 1, message: '账号或密码错误'})
    }
  })
});


app.listen(8080, () => {
  console.log('服务器启动成功');
})

